package com.icehand.wechat.js;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.icehand.common.constants.CommonConstants;
import com.icehand.wechat.code.WechatErrorCode;
import com.icehand.wechat.exception.WechatException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @author icehand
 */
@Slf4j
@CacheConfig(cacheNames = "wechat-js")
public class WechatJsHelper {
    private static final String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    private final RestTemplate restTemplate;

    public WechatJsHelper(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     *
     * @param appId appId
     * @param secret secret
     * @param code code
     * @return openId
     */
    @Cacheable(key = "'openid:'+#appId+':'+#uid",condition = "#uid !=null")
    public String getWeChatOpenId(String appId, Long uid, String secret,String code){
        if(Strings.isNullOrEmpty(appId) || Strings.isNullOrEmpty(secret) || Strings.isNullOrEmpty(code)){
            throw new WechatException("check param fail, appId or secret or code is empty");
        }

        String result = restTemplate.getForObject(String.format(TOKEN_URL,appId,secret,code),String.class);
        if(StringUtils.isEmpty(result)){
            throw new WechatException("request wechat js openId fail");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.containsKey(CommonConstants.K_ERR_CODE)){
            throw new WechatException(WechatErrorCode.choice(jsonObject.getInteger(CommonConstants.K_ERR_CODE)).getMsg());
        }
        return jsonObject.getString("openid");
    }
}
